#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

#define ERR_EXIT(m) \
do{\
perror(m);\
exit(EXIT_FAILURE);\
}while(0)

int main()
{
    //读端
    umask(0);//定好掩码的值--避免后续受到影响
    //创建命名管道---kedukexie
    if(mkfifo("mypipe", 0664) < 0)
    {
        ERR_EXIT("mkfifo");
    }

    int rfd = open("mypipe", O_RDONLY);
    if(rfd == -1) ERR_EXIT("open");

    char buf[1024];

    //一直保持接受信息--死循环
    while(1)
    {
        buf[0] = 0;
        printf("Wait...\n");
        ssize_t s = read(rfd, buf, sizeof(buf) - 1);
        if(s < 0) ERR_EXIT("read");
        //成功安全退出
        else if(s == 0) 
        {
            printf("client quit, exit now\n");
            exit((EXIT_SUCCESS));
        }
        //接受信息
        else
        {
            buf[s - 1] = 0;
            printf("client say : %s\n", buf);
        }
    }

    close(rfd);

    return 0;
}